<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="教案名字" prop="lplanName">
        <el-input
          v-model="queryParams.lplanName"
          placeholder="请输入教案名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['TecherLessonPlan:TecherLessonPlan:add']"
        >新增教案
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="goAiLessonPlan"
          v-hasPermi="['TecherLessonPlan:TecherLessonPlan:add']"
        >AI生成教案
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['TecherLessonPlan:TecherLessonPlan:edit']"
        >修改教案
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['TecherLessonPlan:TecherLessonPlan:remove']"
        >删除教案
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :border="true" v-loading="loading" :data="TecherLessonPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="教案id" align="center" prop="lplanId" />-->
      <!--      <el-table-column label="用户id" align="center" prop="userId" />-->
      <!--      <el-table-column label="部门id" align="center" prop="deptId" />-->
      <el-table-column label="教案名称" align="center" prop="lplanName"/>
      <el-table-column label="教案创建者" align="center" prop="createBy"/>
      <el-table-column label="教案创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="goLessonMainById(scope.row.lplanId)"
            v-hasPermi="['TecherLessonPlan:TecherLessonPlan:edit']"
          >查看详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['TecherLessonPlan:TecherLessonPlan:edit']"
          >修改教案
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['TecherLessonPlan:TecherLessonPlan:remove']"
          >删除教案
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改教案管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id"/>
        </el-form-item>
        <el-form-item label="部门id" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门id"/>
        </el-form-item>
        <el-form-item label="教案名字" prop="lplanName">
          <el-input v-model="form.lplanName" placeholder="请输入教案名字"/>
        </el-form-item>
        <el-form-item label="教案内容">
          <editor v-model="form.lplanMain" :min-height="192"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  listTecherLessonPlan,
  getTecherLessonPlan,
  delTecherLessonPlan,
  addTecherLessonPlan,
  updateTecherLessonPlan,kkk
} from "@/api/TecherLessonPlan/TecherLessonPlan";
// 导入sendMessage函数
import { sendMessage } from "./ttt"
import  { fetchEventSource }from "@microsoft/fetch-event-source"
export default {
  name: "TecherLessonPlan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 教案管理表格数据
      TecherLessonPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        lplanName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          {required: true, message: "用户id不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "部门id不能为空", trigger: "blur"}
        ],
        lplanName: [
          {required: true, message: "教案名字不能为空", trigger: "blur"}
        ],
        ss: "",
        lplanMain: [
          {required: true, message: "教案内容不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.sse()
    this.getList();
  },
  methods: {
    sse() {
      const controller = new AbortController()
      const signal = controller.signal
      fetchEventSource( process.env.VUE_APP_BASE_API +
        `/ai/sss`, {
        method: 'POST',
        signal: signal,
        headers: {
          "Accept": "application/json",
          'Content-Type':'text/event-stream,application/json',
          "Authorization":"Bearer 1eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQ4YjM3NjhmLTQzNjQtNGQ2Ny1hYmYyLWM3ZTJkNTc1OGVkYyJ9.vMaCIMm4Zii2OXeWBkrxTHgocrUQXqQAayJRoGAdK4JHhGlrM9p_DvTmwNJudbOwHrnyneKx3odqa4uBiSlZPw"
        },
        body: JSON.stringify("message"),
        onmessage(msg) {
          // console.log(msg.event)
          if (msg.event === '') {
            let result = JSON.parse(msg.data);
            console.log(result)
          } else if (msg.event === 'close') {
            controller.abort();
          }
        },
        onerror(err) {
          throw err; // 或者throw改为其他
        }
      })
  },

    send(){
      // SSE 连接 类似 chatgpt 流数据
      const eventSource = new EventSource(
        process.env.VUE_APP_BASE_API +
        `/sss`
      );
      eventSource.onmessage = (event) => {
        let detail = JSON.parse(event.data);
        console.log(detail)
        if (
          detail.role === "stop"
        ) {
          eventSource.close(); // 终止 SSE
          return false;
        }

      };
      // // 定义要发送的数据
      // const data = {
      //   message: "你是"
      // };
      //
      // // 定义一个回调函数，用于处理接收到的新数据
      // const callback = (jsonData) => {
      //   console.log(9999999)
      //   console.log('Received new data:', jsonData);
      //   // 处理接收到的数据
      // };
      // console.log(callback,"000000000")
      // sendMessage({ data, controller: new AbortController(), callback }).then(res=>{
      //   console.log(res)
      // })


    },




    goAiLessonPlan() {
      this.$router.push("/LessonPlan")
    },
    goLessonMainById(id) {
      this.$router.push("/getLessonPlanMain/index/" + id)
    },
    /** 查询教案管理列表 */
    getList() {
      // kkk({msg:"你好"},(progressEvent)=> {
      //   // 这里你可以实时获取到下载进度信息
      //   // console.log(progressEvent);
      //   // 你可以根据progressEvent来更新页面上的进度条或者其他UI元素
      // }).then(res=>{
      //   const dataStream = Readable.from(res.data)
      //   // 监听数据流
      //   dataStream.on('data', (chunk) =>{
      //     // 可在此添加一些自己的中间层处理逻辑
      //   console.log(chunk)
      // })
      // })
      this.loading = true;
      listTecherLessonPlan(this.queryParams).then(response => {
        this.TecherLessonPlanList = response.rows;
        this.total = response.total;
        this.loading = false;

      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lplanId: null,
        userId: null,
        deptId: null,
        lplanName: null,
        lplanMain: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lplanId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加教案管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lplanId = row.lplanId || this.ids
      
      this.$router.push("/getLessonPlanMain/editorLessonPlan/" + lplanId)
      // getTecherLessonPlan(lplanId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改教案管理";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lplanId != null) {
            updateTecherLessonPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTecherLessonPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lplanIds = row.lplanId || this.ids;
      this.$modal.confirm('是否确认删除教案管理编号为"' + lplanIds + '"的数据项？').then(function () {
        return delTecherLessonPlan(lplanIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('TecherLessonPlan/TecherLessonPlan/export', {
        ...this.queryParams
      }, `TecherLessonPlan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
